<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
// 引入 useRouter 函数
import { useRouter } from 'vue-router'
// 引入 ElMessageBox
import { ElMessageBox, ElMessage, ElDialog, ElInput } from 'element-plus'
// 状态类型映射
const statusTypeMap = {
  pending: 'warning',
  processing: 'primary',
  completed: 'success',
}

const statusLabels = {
  pending: '未标注',
  processing: '标注中',
  completed: '已完成',
}

// 示例数据
const annotationTasks = ref([
  {
    id: 1,
    name: '大狗检测',
    description: '检测大狗品种及位置',
    status: 'pending',
  },
  {
    id: 2,
    name: '卡皮巴拉检测',
    description: '卡皮巴拉行为分析数据集',
    status: 'processing',
  },
  {
    id: 3,
    name: '小狗检测',
    description: '小型犬分类标注',
    status: 'completed',
  },
])
interface Dataset {
  id: string
  name: string
  status: 'raw' | 'formatted' | 'filtered'
  progress: number
  isImporting: boolean // 新增导入状态
  isFormatting: boolean // 新增格式化状态
  files: FileInfo[] // 替换原来的fileCount字段
}
// 新增文件信息接口
interface FileInfo {
  id: string
  name: string
  type: 'image' | 'video' | 'audio'
  size: number
  path: string
}
const handleSelectionChange = (selectedRows: Dataset[]) => {
  selectedDatasets.value = selectedRows.map((row) => row.id)
}
const showPackageDialog = ref(false)
const selectedDatasets = ref<string[]>([])
// const availableDatasets = ref<Dataset[]>([]) // 需要从DataProcess组件获取或通过API获取
const showCreateDialog = ref(false)
const isEditing = ref(false) // 新增编辑状态标识
// 修改任务表单结构
const taskForm = ref({
  id: null as number | null, // 新增任务ID字段
  name: '',
  description: '',
  images: [] as FileInfo[],
})

const handleCreate = () => {
  isEditing.value = false
  showCreateDialog.value = true
  // 重置表单数据
  taskForm.value = {
    id: null,
    name: '',
    description: '',
    images: [],
  }
  console.log('新建标注任务')
}
const availableDatasets = reactive<Dataset[]>([
  {
    id: '1',
    name: '数据集1',
    status: 'filtered',
    progress: 0,
    isImporting: false,
    isFormatting: false,
    files: [
      {
        id: '1-1',
        name: 'image1.jpg',
        type: 'image',
        size: 1024,
        path: 'C:/Users/Huang Z/vueProjects/viewPage/pdf1.png',
      },
      {
        id: '1-2',
        name: 'image2.jpg',
        type: 'image',
        size: 1024,
        path: 'C:/Users/Huang Z/vueProjects/viewPage/pdf2.png',
      },
      {
        id: '1-3',
        name: 'image3.jpg',
        type: 'image',
        size: 1024,
        path: 'C:/Users/Huang Z/vueProjects/viewPage/pdf3.png',
      },
      {
        id: '1-4',
        name: 'image4.jpg',
        type: 'image',
        size: 1024,
        path: 'C:/Users/Huang Z/vueProjects/viewPage/pdf4.png',
      },
      {
        id: '1-5',
        name: 'image5.jpg',
        type: 'image',
        size: 1024,
        path: 'C:/Users/Huang Z/vueProjects/viewPage/pdf5.png',
      },
      {
        id: '1-6',
        name: 'image6.jpg',
        type: 'image',
        size: 1024,
        path: 'C:/Users/Huang Z/vueProjects/viewPage/pdf6.png',
      },
      {
        id: '1-7',
        name: 'image7.jpg',
        type: 'image',
        size: 1024,
        path: 'C:/Users/Huang Z/vueProjects/viewPage/pdf7.png',
      },
      {
        id: '1-8',
        name: 'image8.jpg',
        type: 'image',
        size: 1024,
        path: 'C:/Users/Huang Z/vueProjects/viewPage/pdf8.png',
      },
      {
        id: '1-9',
        name: 'image9.jpg',
        type: 'image',
        size: 1024,
        path: 'C:/Users/Huang Z/vueProjects/viewPage/pdf9.png',
      },
      {
        id: '1-10',
        name: 'image10.jpg',
        type: 'image',
        size: 1024,
        path: 'C:/Users/Huang Z/vueProjects/viewPage/pdf10.png',
      },
      // 添加更多文件...
    ],
  },
  // 其他数据集...
])

// 添加确认选择方法
const confirmPackageSelection = async () => {
  // 获取选中数据集ID列表
  const selectedIds = selectedDatasets.value
  // 筛选出选中数据集的所有文件
  const selectedFiles = availableDatasets
    .filter((dataset) => selectedIds.includes(dataset.id))
    .flatMap((dataset) => dataset.files)
    .map((file) => ({
      ...file,
      // 转换本地路径为可访问路径（重要！）
      path: file.path.replace('C:/Users/Huang Z/vueProjects/viewPage/', './'),
    }))

  // 合并并更新图片列表（保持响应式）
  taskForm.value.images = [...taskForm.value.images, ...selectedFiles]
  if (isEditing.value && taskForm.value.id) {
    // 更新现有任务
    const index = annotationTasks.value.findIndex((t) => t.id === taskForm.value.id)
    if (index !== -1) {
      annotationTasks.value[index] = {
        ...annotationTasks.value[index],
        name: taskForm.value.name,
        description: taskForm.value.description,
        files: selectedFiles,
      }
    }
  } else {
    // 创建新标注任务
    const newTask = {
      id: Math.max(...annotationTasks.value.map((t) => t.id)) + 1,
      name: `标注任务-${new Date().toLocaleString()}`,
      description: `包含${selectedFiles.length}个文件的标注任务`,
      status: 'pending',
      files: selectedFiles, // 直接使用选中的文件
    }

    // 添加到任务列表
    annotationTasks.value.push(newTask)
  }
  // 重置选择并关闭弹窗
  selectedDatasets.value = []
  showPackageDialog.value = false
  ElMessage.success(`已创建包含${selectedFiles.length}个文件的新标注任务`)
}
// 弹窗相关方法
const handleUpload = () => {
  // 这里应该替换为实际获取已筛选数据集的逻辑
  // availableDatasets.value = [
  //   // 示例数据，实际应从DataProcess组件获取
  //   {
  //     id: '1',
  //     name: '已筛选数据集',
  //     status: 'filtered',
  //     files: [{ id: '1', name: 'dog.jpg', type: 'image', size: 1024, path: '/images/dog.jpg' }],
  //   },
  // ]
  //获取数据集
  availableDatasets.name = '已筛选数据集'
  showPackageDialog.value = true
}

// // 操作处理函数
// const handleCreateAnnotation = () => {
//   console.log('新建标注任务')
// }

const handleDownload = () => {
  console.log('导出数据集')
}
// 在setup上下文中获取router实例
const router = useRouter()
// 修改handleEdit方法
const handleEdit = (row: any) => {
  isEditing.value = true
  showCreateDialog.value = true
  // 回填当前任务数据
  taskForm.value = {
    id: row.id,
    name: row.name,
    description: row.description,
    images: row.files || [], // 假设任务数据存储在files字段
  }
}

const handleAnnotate = (row: any) => {
  router.push({
    path: `/dataAnnotation-annotation/${row.id}`,
    query: { taskName: row.name }, // 添加任务名称参数
  })
}

const handleCopy = (row: any) => {
  const currentIndex = annotationTasks.value.findIndex((t) => t.id === row.id)
  const maxId = Math.max(...annotationTasks.value.map((t) => t.id))

  const newTask = {
    ...row,
    id: maxId + 1,
    name: `${row.name}_1`,
    status: 'pending', // 新任务重置为未标注状态
  }

  annotationTasks.value.splice(currentIndex + 1, 0, newTask)
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定删除该标注任务？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      annotationTasks.value = annotationTasks.value.filter((task) => task.id !== row.id)
      ElMessage.success('删除成功')
    })
    .catch(() => {
      // 用户取消操作
    })
}

const handleShare = (row: any) => {
  console.log('分享任务:', row)
}
</script>

<template>
  <div class="annotation-container">
    <!-- 操作工具栏 -->
    <div class="action-toolbar">
      <el-button type="primary" icon="Plus" @click="handleCreate">新建标注任务</el-button>
      <el-button type="success" icon="Download" @click="handleDownload">导出数据集</el-button>
    </div>

    <!-- 任务表格区 -->
    <el-table :data="annotationTasks" style="width: 100%" height="calc(100vh - 180px)" border>
      <el-table-column prop="name" label="标注任务" width="200">
        <template #default="{ row }">
          <span class="task-name">{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="description" label="描述" min-width="300" />

      <el-table-column prop="status" label="状态" width="150">
        <template #default="{ row }">
          <el-tag :type="statusTypeMap[row.status]">
            {{ statusLabels[row.status] }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="320">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="primary"
            :disabled="row.status === 'completed'"
            @click="handleAnnotate(row)"
          >
            标注
          </el-button>
          <el-button size="small" @click="handleCopy(row)">复制</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)"> 删除 </el-button>
          <el-button size="small" type="success" @click="handleShare(row)"> 分享 </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-dialog
    v-model="showCreateDialog"
    :title="isEditing ? '编辑标注任务' : '新建标注任务'"
    width="800px"
    custom-class="create-dialog"
  >
    <div class="dialog-content">
      <!-- 顶部名称输入 -->
      <div class="dialog-header">
        <el-input
          v-model="taskForm.name"
          :placeholder="isEditing ? '编辑任务名称' : '请输入标注任务名称'"
          clearable
          style="width: 300px"
        />
      </div>

      <!-- 中央内容区 -->
      <div class="dialog-body">
        <el-row :gutter="20">
          <!-- 左侧图片面板 -->
          <el-col :span="16">
            <div class="image-panel">
              <div
                v-if="taskForm.images.length === 0"
                @click="handleUpload"
                class="upload-placeholder"
              >
                <el-icon><Upload /></el-icon>
                <p>添加图片，仅显示筛选完成的包，供用户选择要添加的图</p>
              </div>
              <div v-else class="image-grid">
                <div v-for="(file, index) in taskForm.images" :key="index" class="image-item">
                  <img :src="file.path" :alt="file.name" class="preview-image" />
                </div>
              </div>
            </div>
          </el-col>

          <!-- 右侧描述输入 -->
          <el-col :span="8" style="height: 400px">
            <el-input
              v-model="taskForm.description"
              type="textarea"
              placeholder="请输入任务描述"
              resize="none"
              style="height: 100%; min-height: 400px; box-sizing: border-box"
            />
          </el-col>
        </el-row>
      </div>

      <!-- 底部操作栏 -->
      <div class="dialog-footer">
        <div class="footer-actions">
          <el-button text @click="showCreateDialog = false">返回</el-button>
          <div class="action-buttons">
            <el-button @click="handleRefresh">刷新</el-button>
            <el-button type="primary" @click="handleUpload">添加</el-button>
            <el-button @click="handleMultiSelect">多选</el-button>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
  <el-dialog
    v-model="showPackageDialog"
    title="选择您的数据包"
    width="800px"
    custom-class="package-dialog"
  >
    <div class="dialog-content">
      <el-checkbox-group v-model="selectedDatasets">
        <el-table
          :data="availableDatasets"
          style="width: 100%"
          row-key="id"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" :reserve-selection="true" />
          <el-table-column prop="name" label="数据集名称" />
          <el-table-column label="文件数量" width="120">
            <template #default="{ row }">
              <el-tag type="info">{{ row.files?.length || 0 }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-checkbox-group>

      <div class="dialog-footer">
        <el-button @click="showPackageDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmPackageSelection">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped>
.create-dialog {
  .dialog-content {
    display: flex;
    flex-direction: column;
    height: 70vh;
    max-height: 800px;
  }

  .el-row {
    height: 100% !important;
    
    min-height: 0;
    margin: 0 !important;

    > .el-col {
      height: 100%;
      min-height: 0;
      display: flex;
      flex-direction: column;
    }
  }

  .dialog-body {
    flex: 1;
    min-height: 0;
    margin: 20px 0;
    overflow: hidden;
  }

  .image-panel {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .image-grid {
      flex: 1;
      min-height: 0;
      overflow-y: auto;
      padding: 10px;
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
      gap: 10px;
      align-content: flex-start;
      grid-auto-rows: min-content;
      scrollbar-width: thin !important;
      &::-webkit-scrollbar {
        width: 8px !important;
      }
    }
  }

  :deep(.el-col) {
    display: flex !important;
    flex-direction: column;
  }
}

.annotation-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  height: 100%;
}

.action-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.task-name {
  font-weight: 500;
}

/* 表格样式 */
:deep(.el-table th) {
  font-weight: 600;
  background-color: #f8fafc;
}

:deep(.el-table--border) {
  border-radius: 8px;
  overflow: hidden;
}

.image-panel {
  /* 添加滚动条 */
  overflow-y: auto;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 10px;
  padding: 10px;
}

.image-item {
  width: 100%;
  aspect-ratio: 1;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
